package com.charley.icloud.admin.webapps.sysrole.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import com.charley.icloud.admin.webapps.sysmenu.dao.SysMenuMapper;
import com.charley.icloud.admin.webapps.sysmenu.pojo.entity.SysMenuDO;
import com.charley.icloud.admin.webapps.sysrole.dao.SysRoleMapper;
import com.charley.icloud.admin.webapps.sysrole.pojo.entity.SysRoleDO;
import com.charley.icloud.admin.webapps.sysrole.pojo.entity.SysRoleMenu;
import com.charley.icloud.admin.webapps.sysrole.pojo.model.SysRoleVO;
import com.charley.icloud.admin.webapps.sysrole.pojo.request.SysRoleMenuQuery;
import com.charley.icloud.admin.webapps.sysrole.pojo.request.SysRoleQuery;
import com.charley.icloud.admin.webapps.sysrole.service.SysRoleService;
import com.charley.icloud.common.constants.SystemNumberConstants;
import com.charley.icloud.common.response.result.HttpResponseResult;
import com.charley.icloud.admin.common.constant.SysTableConstants;
import com.charley.icloud.common.response.result.HttpResponseResultFactory;
import com.charley.icloud.datasource.page.PageRequest;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/sys/role")
@Tag(name = "角色控制器")
public class SysRoleController {

    @Resource
    private SysRoleService sysRoleService;
    @Resource
    private SysRoleMapper sysRoleMapper;
    @Resource
    private SysMenuMapper sysMenuMapper;


    @PostMapping(value = "/save")
    @Operation(summary = "保存角色", description = "后台管理系统")
    public HttpResponseResult save(@RequestBody SysRoleQuery query) {
        SysRoleDO role = sysRoleService.findById(query.getId());
        if (role != null) {
            if (SysTableConstants.SYS_ROLE_TABLE_TYPE_SUPER_ADMIN.equals(role.getType())) {
                return HttpResponseResultFactory.fail("超级管理员不允许修改!");
            }
        }
        // 新增角色
        if ((query.getId() == null || query.getId() == 0) && !sysRoleService.findByName(query.getName()).isEmpty()) {
            return HttpResponseResultFactory.fail("角色名已存在!");
        }
        SysRoleDO record = new SysRoleDO();
        BeanUtil.copyProperties(query, record, CopyOptions.create().ignoreCase().ignoreNullValue());
        return HttpResponseResultFactory.success(sysRoleService.save(record));
    }

    @PostMapping(value = "/delete")
    @Operation(summary = "删除角色", description = "后台管理系统")
    public HttpResponseResult delete(@RequestBody List<SysRoleQuery> queries) {
        List<SysRoleDO> records = new ArrayList<>();
        if (queries != null && queries.size() > SystemNumberConstants.SYSTEM_NUMBER_INTEGER_ZERO) {
            for (SysRoleQuery query : queries) {
                SysRoleDO role = sysRoleService.findById(query.getId());
                if (role != null) {
                    if (SysTableConstants.SYS_ROLE_TABLE_TYPE_SUPER_ADMIN.equals(role.getType())) {
                        return HttpResponseResultFactory.fail("超级管理员不允许修改!");
                    }
                }
                SysRoleDO sysRoleDO = new SysRoleDO();
                BeanUtil.copyProperties(query, sysRoleDO, CopyOptions.create().ignoreCase().ignoreNullValue());
                records.add(sysRoleDO);
            }
        }
        return HttpResponseResultFactory.success(sysRoleService.delete(records));
    }

    @PostMapping(value = "/findPage")
    @Operation(summary = "分页查询", description = "后台管理系统")
    public HttpResponseResult findPage(@RequestBody PageRequest pageRequest) {
        return HttpResponseResultFactory.success(sysRoleService.findPage(pageRequest));
    }

    @GetMapping(value = "/findAll")
    @Operation(summary = "查询所有", description = "后台管理系统")
    public HttpResponseResult findAll() {
        List<SysRoleDO> sysRoleDOS = sysRoleService.findAll();
        if(sysRoleDOS != null && sysRoleDOS.size() > SystemNumberConstants.SYSTEM_NUMBER_INTEGER_ZERO){
            List<SysRoleVO> sysRoleVOS = new ArrayList<>();
            for (SysRoleDO sysRoleDO : sysRoleDOS) {
                SysRoleVO temp = new SysRoleVO();
                BeanUtil.copyProperties(sysRoleDO, temp, CopyOptions.create().ignoreCase().ignoreNullValue());
                sysRoleVOS.add(temp);
            }
            return HttpResponseResultFactory.success(sysRoleVOS);
        }
        return HttpResponseResultFactory.fail("网络延迟，请稍后再试...");
    }

    @GetMapping(value = "/findRoleMenus")
    @Operation(summary = "查询角色菜单", description = "后台管理系统")
    public HttpResponseResult findRoleMenus(@RequestParam Long roleId) {
        return HttpResponseResultFactory.success(sysRoleService.findRoleMenus(roleId));
    }

    @PostMapping(value = "/saveRoleMenus")
    @Operation(summary = "保存角色菜单", description = "后台管理系统")
    public HttpResponseResult saveRoleMenus(@RequestBody SysRoleMenuQuery queries) {

        List<SysRoleMenu> records = new ArrayList<>();
        if (queries != null && !queries.getMenuIds().isEmpty()) {
            if (queries.getId()==null || SystemNumberConstants.SYSTEM_NUMBER_LONG_ZERO.equals(queries.getId())){
                // 新增逻辑
                // 判断角色新增的菜单是否已经被新增过 两个集合求交集，若不为空则表示该角色已经添加过该菜单，不需要再添加
                List<Long> menusOfRole = sysRoleMapper.findAllMenuOfRole(queries.getRoleId());
                // 交集
                Collection<Long> intersection = CollectionUtils.intersection(menusOfRole, queries.getMenuIds());
                if(!intersection.isEmpty()){ // 非空
                    StringBuilder sbMenu = new StringBuilder("该角色已经包含以下菜单：[ ");
                    for (Long menuId : intersection) {
                        SysMenuDO sysMenuDO = sysMenuMapper.selectByPrimaryKey(menuId);
                        sbMenu.append(sysMenuDO.getName()).append(" ");
                    }
                    sbMenu.append("]");
                    return HttpResponseResultFactory.fail(sbMenu.toString());
                }
                for (Long menuId : queries.getMenuIds()) {
                    SysRoleMenu sysRoleMenu = new SysRoleMenu();
                    sysRoleMenu.setRoleId(queries.getRoleId());
                    sysRoleMenu.setMenuId(menuId);
                    sysRoleMenu.setCreateBy("System");
                    sysRoleMenu.setCreateTime(new Date());
                    records.add(sysRoleMenu);
                }
            }else {
                // 修改菜单
                SysRoleDO sysRole = sysRoleMapper.selectByPrimaryKey(queries.getRoleId());
                if (SysTableConstants.SYS_USER_TABLE_TYPE_SUPER_ADMIN.equals(sysRole.getType())) {
                    // 如果是超级管理员，不允许修改
                    return HttpResponseResultFactory.fail("超级管理员拥有所有菜单权限，不允许修改！");
                }
                SysRoleMenu sysRoleMenu = new SysRoleMenu();
                BeanUtil.copyProperties(queries,sysRoleMenu, CopyOptions.create().ignoreCase().ignoreNullValue());
                sysRoleMenu.setMenuId(queries.getMenuIds().get(0));
                sysRoleMenu.setLastUpdateBy("System");
                sysRoleMenu.setLastUpdateTime(new Date());
                records.add(sysRoleMenu);
            }
        }
        return HttpResponseResultFactory.success(sysRoleService.saveRoleMenus(records));
    }

}
